package com.demo.scan;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.pda.scan.ScanThread;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
	private static String TAG = MainActivity.class.getSimpleName();

	/** UI **/
	private EditText eidtBarCount;
	private Button buttonClear;
	private ListView listViewData;
	private CheckBox checkBoxPer;
	private Button buttonScan;
	private Button buttonExit;

	private ScanThread scanThread;
	private List<Barcode> listBarcode = new ArrayList<Barcode>();
	private List<Map<String, String>> listMap;
	private SimpleAdapter adapter = null;

	private boolean mIsContinuous = false;

	private Timer scanTimer = null;

	private KeyReceiver keyReceiver;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == ScanThread.SCAN) {
				String data = msg.getData().getString("data");
				Log.e(TAG, "data = " + data);
				if (data == null || data.equals("")) {
					if (mIsContinuous) {
						scanThread.scan();
					}
					return;
				}
//				Toast.makeText(getApplicationContext(), data, 0).show();
				sortAndadd(listBarcode, data);
				addListView();
				eidtBarCount.setText(listBarcode.size() + "");
				Util.play(1, 0);
				if (mIsContinuous) {
					scanThread.scan();
				}
			}
		};
	};

	private void addListView() {
		listMap = new ArrayList<Map<String, String>>();
		int id = 1;
		for (Barcode barcode : listBarcode) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", id + "");
			map.put("barcode", barcode.getBarcode());
			map.put("count", barcode.getCount() + "");
			listMap.add(map);
		}
		adapter = new SimpleAdapter(this, listMap, R.layout.listview_item,
				new String[] { "id", "barcode", "count", }, new int[] {
				R.id.textView_list_item_id,
				R.id.textView_list_item_barcode,
				R.id.textView_list_item_count });
		listViewData.setAdapter(adapter);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// set HOME key scan
		getWindow().addFlags(0x80000000);
		super.onCreate(savedInstanceState);
		setTitle(getAppVersionName(this));
		setContentView(R.layout.activity_main);
		initView();
		//保持屏幕常亮
		Window window = this.getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		try {
			scanThread = new ScanThread(mHandler);
		} catch (Exception e) {
			// 出现异常
			Toast.makeText(getApplicationContext(), "serialport init fail", 0)
					.show();
			return;
			// e.printStackTrace();
		}
		scanThread.start();
		//init sound
		Util.initSoundPool(this);

		//注册按键广播接收者
		keyReceiver = new KeyReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.rfid.FUN_KEY");
		filter.addAction("android.intent.action.FUN_KEY");
		registerReceiver(keyReceiver , filter);
	}

	/**
	 * 返回当前程序版本名
	 */
	public static String getAppVersionName(Context context) {
		String versionName = "";
		try {
			// ---get the package info---
			PackageManager pm = context.getPackageManager();
			PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				return "";
			}
		} catch (Exception e) {
			Log.e("VersionInfo", "Exception", e);
		}
		return context.getString(R.string.app_name) + "-v" + versionName;
	}

	private List<Barcode> sortAndadd(List<Barcode> list, String barcode) {
		Barcode goods = new Barcode();
		goods.setBarcode(barcode);
		int temp = 1;
		if (list == null || list.size() == 0) {
			goods.setCount(temp);
			list.add(goods);
			return list;
		}

		for (int i = 0; i < list.size(); i++) {
			if (barcode.equals(list.get(i).getBarcode())) {
				temp = list.get(i).getCount() + temp;
				goods.setCount(temp);
				for (int j = i; j > 0; j--) {
					list.set(j, list.get(j - 1));
				}
				list.set(0, goods);
				return list;
			}
		}
		//
		Barcode lastgoods = list.get(list.size() - 1);
		for (int j = list.size() - 1; j >= 0; j--) {
			if (j == 0) {
				goods.setCount(temp);
				list.set(j, goods);
			} else {
				list.set(j, list.get(j - 1));
			}

		}
		list.add(lastgoods);
		return list;
	}

	long exitSytemTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_HOME) {
			scanThread.scan();
		}

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (System.currentTimeMillis() - exitSytemTime > 2000) {
				Toast.makeText(getApplicationContext(), R.string.exitSystem,
						Toast.LENGTH_SHORT).show();
				exitSytemTime = System.currentTimeMillis();
				return true;
			} else {
				finish();
			}

		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		if(scanTimer!= null){
			scanTimer.cancel();
		}
		if (scanThread != null) {
			scanThread.interrupt();
			scanThread.close();
		}

		//注销广播接收者
		unregisterReceiver(keyReceiver);
		super.onDestroy();
	}

	private void initView() {
		eidtBarCount = (EditText) findViewById(R.id.editText_barcode_count);
		buttonClear = (Button) findViewById(R.id.button_clear);
		listViewData = (ListView) findViewById(R.id.listView_data_list);
		checkBoxPer = (CheckBox) findViewById(R.id.checkbox_per_100ms);
		buttonScan = (Button) findViewById(R.id.button_scan);
		buttonExit = (Button) findViewById(R.id.button_exit);

		buttonScan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				scanThread.scan();

			}
		});
		checkBoxPer.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					buttonScan.setClickable(false);
					buttonScan.setTextColor(Color.GRAY);
//					scanTimer = new Timer();
//					scanTimer.schedule(new TimerTask() {
//
//						@Override
//						public void run() {
//							if(scanThread != null){
//								scanThread.scan();
//							}
//
//						}
//					}, 100, 200);
					mIsContinuous = true;
					scanThread.scan();
				}else{
					mIsContinuous = false;
					buttonScan.setClickable(true);
					buttonScan.setTextColor(Color.BLACK);
//					if(scanTimer != null){
//						scanTimer.cancel();
//					}
					scanThread.stopScan();
				}

			}
		});

		buttonClear.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				eidtBarCount.setText("");
				listBarcode.removeAll(listBarcode);
				listViewData.setAdapter(null);
			}
		});

		buttonExit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();
			}
		});

	}

	/**
	 * 按键广播接收者 用于接受按键广播 触发扫描
	 */
	private boolean mIsPressed = false;
	private class KeyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			int keyCode = intent.getIntExtra("keyCode", 0);
			// 为兼容早期版本机器
			if (keyCode == 0) {
				keyCode = intent.getIntExtra("keycode", 0);
			}
			boolean keyDown = intent.getBooleanExtra("keydown", false);
			if (keyDown && !mIsPressed) {
				// 根据需要在对应的按键的键值中开启扫描,
				switch (keyCode) {
					case KeyEvent.KEYCODE_F1:

					case KeyEvent.KEYCODE_F2:

					case KeyEvent.KEYCODE_F3:

					case KeyEvent.KEYCODE_F4:

					case KeyEvent.KEYCODE_F5:

					default:
						//开启扫描
						mIsPressed = true;
						scanThread.scan();
						break;
				}
			}else {
				mIsPressed = false;
			}
		}
	}

}
